import React, { useState, useEffect } from "react";
import {
  Table,
  Input,
  Button,
  message,
  Select,
  Modal,
} from "antd";
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import axios from "axios";
import CommonFormModal from "../../components/CommonFormModal";
import { useFormModal } from "../../hooks/useFormModal";
import { fieldFormConfig } from "../../utils/formConfigs";

// API基础URL
const API_BASE_URL = "http://localhost:3000";

const { Option } = Select;

// 定义字段数据类型
interface Field {
  key: string;
  id: string;
  code: string;
  name: string;
  description: string;
  type: string;
  creator: string;
  createTime: string;
  modifier: string;
  modifyTime: string;
}

const Field: React.FC = () => {
  const [fieldData, setFieldData] = useState<Field[]>([]);
  const [filteredData, setFilteredData] = useState<Field[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    name: "",
    type: "",
  });
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 使用通用表单Hook
  const {
    visible,
    isAddMode,
    currentRecord,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    loading: _modalLoading,
    openAddModal,
    openEditModal,
    closeModal,
  } = useFormModal<Field>();

  // 获取字段数据
  const fetchFields = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/foundation/fields`);
      setFieldData(response.data);
      setFilteredData(response.data);
    } catch (error) {
      console.error('获取字段数据失败:', error);
      message.error('获取字段数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchFields();
  }, []);

  // 处理搜索
  const handleSearch = () => {
    const filtered = fieldData.filter((item) => {
      return (
        (searchParams.name === "" ||
          item.name.toLowerCase().includes(searchParams.name.toLowerCase())) &&
        (searchParams.type === "" || item.type === searchParams.type)
      );
    });
    setFilteredData(filtered);
    setCurrentPage(1);
    message.success(`找到 ${filtered.length} 条匹配记录`);
  };

  // 处理重置
  const handleReset = () => {
    setSearchParams({
      name: "",
      type: "",
    });
    setFilteredData(fieldData);
    setCurrentPage(1);
    message.info("已重置搜索条件");
  };

  // 打开新增字段弹窗
  const handleAddField = () => {
    openAddModal();
  };

  // 打开编辑弹窗
  const handleEdit = (record: Field) => {
    openEditModal(record);
  };

  // 确认删除
  const handleDelete = (record: Field) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除字段"${record.name}"吗？`,
      async onOk() {
        try {
          await axios.delete(`${API_BASE_URL}/api/foundation/fields/${record.id}`);
          // 重新获取数据
          await fetchFields();
          message.success("删除成功");
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      },
    });
  };

  // 处理表单提交
  const handleSubmit = async (values: Field, isAddMode: boolean, currentRecord?: Field | null) => {
    try {
      if (isAddMode) {
        // 新增
        await axios.post(`${API_BASE_URL}/api/foundation/fields`, {
          name: values.name,
          description: values.description,
          type: values.type,
        });
        
        // 重新获取数据
        await fetchFields();
        message.success("新增成功");
      } else {
        // 编辑
        await axios.put(`${API_BASE_URL}/api/foundation/fields/${currentRecord?.id}`, {
          name: values.name,
          description: values.description,
          type: values.type,
        });
        
        // 重新获取数据
        await fetchFields();
        message.success("编辑成功");
      }
      
      // 操作成功后关闭弹窗
      closeModal();
    } catch (error) {
      console.error('操作失败:', error);
      message.error(isAddMode ? '新增失败' : '编辑失败');
    }
  };

  // 表格列定义
  const columns = [
    {
      title: "",
      dataIndex: "checkbox",
      width: 50,
      render: (_: unknown, record: Field) => (
        <input
          type="checkbox"
          checked={selectedRows.includes(record.key)}
          onChange={(e) => {
            if (e.target.checked) {
              setSelectedRows([...selectedRows, record.key]);
            } else {
              setSelectedRows(selectedRows.filter((key) => key !== record.key));
            }
          }}
        />
      ),
    },
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      width: 80,
    },
    {
      title: "编码",
      dataIndex: "code",
      key: "code",
      width: 100,
    },
    {
      title: "字段名称",
      dataIndex: "name",
      key: "name",
      width: 150,
    },
    {
      title: "说明",
      dataIndex: "description",
      key: "description",
      width: 150,
    },
    {
      title: "类型",
      dataIndex: "type",
      key: "type",
      width: 120,
    },
    {
      title: "创建人",
      dataIndex: "creator",
      key: "creator",
      width: 100,
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      width: 120,
    },
    {
      title: "修改人",
      dataIndex: "modifier",
      key: "modifier",
      width: 100,
    },
    {
      title: "修改时间",
      dataIndex: "modifyTime",
      key: "modifyTime",
      width: 120,
    },
    {
      title: "操作",
      key: "operation",
      width: 150,
      render: (_: unknown, record: Field) => (
        <div style={{ display: 'flex', gap: '8px', alignItems: 'center', whiteSpace: 'nowrap' }}>
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              handleEdit(record);
            }}
            style={{ whiteSpace: 'nowrap' }}
          >
            <EditOutlined style={{ fontSize: "14px" }} /> 编辑
          </a>
          <a
            href="#"
            onClick={(e) => {
              e.preventDefault();
              handleDelete(record);
            }}
            style={{ whiteSpace: 'nowrap' }}
          >
            <DeleteOutlined style={{ fontSize: "14px" }} /> 删除
          </a>
        </div>
      ),
    },
  ];

  // 分页配置
  const pagination = {
    current: currentPage,
    pageSize: pageSize,
    total: filteredData.length,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) =>
      `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
    onChange: (page: number, size: number) => {
      setCurrentPage(page);
      setPageSize(size);
    },
    onShowSizeChange: (current: number, size: number) => {
      setCurrentPage(1);
      setPageSize(size);
    },
  };

  return (
    <div style={{ padding: "20px", height: "calc(100vh - 64px)", overflow: "hidden" }}>
      {/* 搜索区域 */}
      <div
        style={{
          backgroundColor: "#fff",
          padding: "20px",
          marginBottom: "20px",
          borderRadius: "4px",
        }}
      >
        <div style={{ display: "flex", gap: "16px", marginBottom: "16px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
            <SearchOutlined />
            <Input
              placeholder="请输入字段名称"
              value={searchParams.name}
              onChange={(e) =>
                setSearchParams({ ...searchParams, name: e.target.value })
              }
              style={{ width: "200px" }}
            />
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
            <Select
              placeholder="请选择字段类型"
              value={searchParams.type}
              onChange={(value) =>
                setSearchParams({ ...searchParams, type: value })
              }
              style={{ width: "200px" }}
              allowClear
            >
              <Option value="客户类型">客户类型</Option>
              <Option value="物品单位">物品单位</Option>
            </Select>
          </div>
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
          <Button onClick={handleReset}>重置</Button>
        </div>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAddField}>
          新增字段
        </Button>
      </div>

      {/* 表格区域 */}
      <Table
          columns={columns}
          dataSource={filteredData}
          pagination={pagination}
          scroll={{ x: 1200, y: "calc(100vh - 500px)" }}
          size="small"
          bordered
          loading={loading}
        />

      {/* 新增/编辑弹窗 */}
      <CommonFormModal
        visible={visible}
        title={isAddMode ? "新增字段" : "编辑字段"}
        isAddMode={isAddMode}
        currentRecord={currentRecord}
        formItems={fieldFormConfig}
        onSubmit={handleSubmit}
        onCancel={closeModal}
        loading={loading}
        width={600}
      />
    </div>
  );
};

export default Field;